"""基金基础信息查询模块"""

NAME_SQL = """
SELECT fa.CHINAME
FROM NA_FUNDARCHIVES fa
"""

NAMECODE_SQL = """
SELECT * FROM
(
    SELECT
        sm.ChiName AS 基金全称,
        sm.ChiNameAbbr AS 基金简称,
        sm.InnerCode AS 内部代码,
        fa.SecurityCode AS 基金代码
    FROM SecuMain sm
    INNER JOIN MF_FundArchives fa ON sm.InnerCode = fa.InnerCode
    WHERE fa.SecurityCode = :fund_code
       OR sm.ChiName LIKE '%' || :fund_name || '%'
       OR sm.ChiNameAbbr LIKE '%' || :fund_name || '%'
    ORDER BY
        CASE 
            WHEN fa.SecurityCode = :fund_code THEN 0
            WHEN sm.ChiName LIKE '%' || :fund_name || '%' THEN INSTR(sm.ChiName, :fund_name)
            WHEN sm.ChiNameAbbr LIKE '%' || :fund_name || '%' THEN INSTR(sm.ChiNameAbbr, :fund_name)
            ELSE 999
        END
)
WHERE ROWNUM < 2
"""

BASE_SQL = """
SELECT * FROM
(
    SELECT
    sm.ChiName AS 基金全称,
    sm.InnerCode AS 内部代码,
    sm.ChiNameAbbr AS 基金简称,
    fa.SecurityCode AS 基金代码,
    fa.FundType AS 基金类型,
    fa.EstablishmentDate AS 基金成立时间,
    fa.Manager AS 基金经理,
    fa.RiskReturncharacter AS 风险收益特征,
    fa.TrusteeCode AS 托管人代码,
    mto.TrusteeName AS 基金托管人,
    fa.PerformanceBenchMark AS 业绩比较基准,
    fa.InvestTarget AS 投资目标,
    fa.InvestField AS 投资对象,
    fa.InvestOrientation AS 主要投资策略
FROM SecuMain sm
INNER JOIN MF_FundArchives fa ON sm.InnerCode = fa.InnerCode
INNER JOIN MF_TrusteeOutline mto ON fa.TrusteeCode = mto.TrusteeCode
WHERE 1=1
    -- 当传入了fund_code时，只查找这一个基金信息
    AND (
        (:fund_code IS NOT NULL AND fa.SecurityCode = :fund_code)
        OR 
        -- 当fund_code为null且fund_name也为null时，查询所有基金
        (:fund_code IS NULL AND :fund_name IS NULL)
        OR
        -- 当fund_code为null但fund_name不为null时，按基金名称模糊查询
        (:fund_code IS NULL AND :fund_name IS NOT NULL AND sm.ChiName LIKE '%' || :fund_name || '%')
    )
ORDER BY
    CASE 
        -- 当按基金代码精确查询时，将该条记录置顶
        WHEN :fund_code IS NOT NULL AND fa.SecurityCode = :fund_code THEN 0
        ELSE 1
    END,
    fa.SecurityCode
)
WHERE ROWNUM < 10000
"""

# 基础信息查询函数
def get_fund_basic_info(fund_code=None, fund_name=None):
    """获取基金基本信息"""
    params = {'fund_code': fund_code, 'fund_name': fund_name}
    # 这里可以添加数据库查询逻辑
    return BASE_SQL, params

def match_fund(fund_code=None, fund_name=None):
    """匹配基金代码和名称"""
    params = {'fund_code': fund_code, 'fund_name': fund_name}
    return NAMECODE_SQL, params